package com.common.base.utils

import android.annotation.SuppressLint
import android.content.ContentUris
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.text.TextUtils
import androidx.core.content.FileProvider
import com.common.base.app.extras.getContext
import com.common.base.app.extras.no
import com.common.base.config.AppConfig.FILE_PRO
import com.yalantis.ucrop.util.FileUtils.*
import java.io.File

/**
 * FileProvider兼容拍照
 */
object FileProvider7 {

    fun getUriForFile(context: Context, file: File): Uri? {
        var fileUri: Uri? = null
        try {
            fileUri = if (Build.VERSION.SDK_INT >= 24) {
                getUriForFile24(context, file)
            } else {
                Uri.fromFile(file)
            }
        } catch (e: Exception) {
            LogUtils.e(e)
        }
        return fileUri
    }

    private fun getUriForFile24(context: Context, file: File): Uri {
        return FileProvider.getUriForFile(
            context,
            context.packageName + FILE_PRO,
            file
        )
    }


    fun setIntentDataAndType(
        context: Context, intent: Intent, type: String, file: File,
        writeAble: Boolean
    ) {
        if (Build.VERSION.SDK_INT >= 24) {
            intent.setDataAndType(getUriForFile(context, file), type)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            if (writeAble) {
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
            }
        } else {
            intent.setDataAndType(Uri.fromFile(file), type)
        }
    }

    fun getPhotoUri(): Uri? {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            getUriAboveAndroidQ()
        } else {
            getUriBelowAndroidQ()
        }
    }


    // 适配android10 创建文件
    private fun getUriAboveAndroidQ(): Uri? {
        val contentValues = ContentValues()
        val fileName = "/IMG_" + System.currentTimeMillis() + ".jpg"
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
        contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/Pictures")
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/JPEG")
        return AppUtils.getContext().contentResolver.insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            contentValues
        )
    }

    //适配Android10版本一下的uri配置
    private fun getUriBelowAndroidQ(): Uri {
        val photoUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            FileProvider.getUriForFile(
                AppUtils.getContext(),
                "${AppUtils.getPackageName()}" + FILE_PRO,
                getFilePath()
            )
        } else {
            Uri.fromFile(getFilePath())
        }
        return photoUri
    }

    //向下兼容
    private fun getFilePath(): File {
        return File(
            checkDirPath(Environment.getExternalStorageDirectory().path + "/DCIM/CATCH/"),
            System.currentTimeMillis().toString() + ".jpg"
        )
    }


    /**
     * 检查文件是否存在
     */
    private fun checkDirPath(dirPath: String?): String? {
        if (TextUtils.isEmpty(dirPath)) {
            return ""
        }
        val dir = File(dirPath)
        if (!dir.exists()) {
            dir.mkdirs()
        }
        return dirPath
    }

    /**
     * 适配Android 4.4及以上,根据uri获取图片的绝对路径
     *
     * @param context 上下文对象
     * @param uri     图片的Uri
     * @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
     */
    @SuppressLint("NewApi")
    fun getRealPathFromUriAboveApiAndroidK(context: Context?, uri: Uri): String? {
        var filePath: String? = null
        if (DocumentsContract.isDocumentUri(context, uri)) {
            // 如果是document类型的 uri, 则通过document id来进行处理
            val documentId = DocumentsContract.getDocumentId(uri)
            if (isMediaDocument(uri)) {
                // 使用':'分割
                val id = documentId.split(":".toRegex()).toTypedArray()[1]
                val selection = MediaStore.Images.Media._ID + "=?"
                val selectionArgs = arrayOf(id)
                filePath = getDataColumn(
                    context,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    selection,
                    selectionArgs
                )
            } else if (isDownloadsDocument(uri)) {
                val contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"),
                    java.lang.Long.valueOf(documentId)
                )
                filePath = getDataColumn(context, contentUri, null, null)
            }
        } else if ("content".equals(uri.scheme, ignoreCase = true)) {
            // 如果是 content 类型的 Uri
            filePath = getDataColumn(context, uri, null, null)
        } else if ("file" == uri.scheme) {
            // 如果是 file 类型的 Uri,直接获取图片对应的路径
            filePath = uri.path
        }
        return filePath
    }

    fun uriToFile(uri: Uri, context: Context): File? {
        var mediaStoreData = ""
        mediaStoreData = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            MediaStore.Images.ImageColumns.RELATIVE_PATH
        } else {
            MediaStore.Images.ImageColumns.DATA
        }
        var path: String? = null
        if ("file" == uri.scheme) {
            path = uri.encodedPath
            if (path != null) {
                path = Uri.decode(path)
                val cr = context.contentResolver
                val buff = StringBuffer()
                buff.append("(").append(mediaStoreData).append("=").append("'$path'").append(")")
                val cur: Cursor? = cr.query(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, arrayOf(
                        MediaStore.Images.ImageColumns._ID,
                        mediaStoreData
                    ), buff.toString(), null, null
                )
                var index = 0
                var dataIdx = 0
                cur?.moveToFirst()
                while (cur?.isAfterLast() == false) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID)
                    index = cur.getInt(index)
                    dataIdx = cur.getColumnIndex(mediaStoreData)
                    path = cur.getString(dataIdx)
                    cur.moveToNext()
                }
                cur?.close()
                if (index == 0) {
                } else {
                    val u = Uri.parse("content://media/external/images/media/$index")
                    println("temp uri is :$u")
                }
            }
            if (path != null) {
                val file = File(path)
                if (!file.exists()) {
                    file.mkdirs()
                }
                return file
            }
        } else if ("content" == uri.scheme) {
            // 4.2.2以后
            val proj = arrayOf(mediaStoreData)
            val cursor: Cursor? = context.contentResolver.query(uri, proj, null, null, null)
            if (cursor?.moveToFirst() == true) {
                val columnIndex: Int = cursor.getColumnIndexOrThrow(mediaStoreData)
                path = cursor.getString(columnIndex)
            }
            cursor?.close()
            val file = File(path)
            if (!file.exists()) {
                file.mkdirs()
            }
            return file
        } else {
            //Log.i(TAG, "Uri Scheme:" + uri.getScheme());
        }
        return null
    }

    fun physical2ContentFile(context: Context, filePath: String, toPackage: String=""):String {
        try {
            // 创建视频文件的File对象
            val file = File(filePath)

            // 获取content URI，为了向外共享我们需要更改这个路径为符合FileProvider的形式
            val contentUri: Uri = FileProvider.getUriForFile(
                context,
                context.packageName + FILE_PRO,
                file
            )

            toPackage.isNullOrEmpty().no {
                getContext().grantUriPermission(
                    toPackage, contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION
                )
            }

            return contentUri.toString()
        } catch (e: Exception) {
            e.printStackTrace()
            // 处理错误情况，例如文件不存在或者FileProvider配置出错
            LogUtils.e("Error while sharing the video")
        }

        return ""
    }
}